package com.jiuqi.abc.model.web;

import com.jiuqi.abc.ABCException;
import com.jiuqi.abc.model.bean.Driver;
import com.jiuqi.abc.model.service.ABCDriverService;
import com.jiuqi.abc.model.service.ABCRelationService;
import com.jiuqi.abc.model.vo.DriverCheckVo;
import com.jiuqi.np.core.restapi.annotation.PermissionsResourceGroup;
import com.jiuqi.nvwa.sf.anno.Licence;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author 龚泽楷
 * @date 2023年05月05日 15:13
 */

@Api(tags = {"abc模型动因管理"})
@RestController
@RequestMapping("abc/model/driver")
@PermissionsResourceGroup("abc模型动因管理")
@Licence(module="com.jiuqi.abc.modelmanager", point="com.jiuqi.abc.function")
public class ABCDriverController {

    @Autowired
    private ABCDriverService abcDriverService;
    
    @Autowired
    private ABCRelationService abcRelationService;

    private static final String CHECK_PASS_AND_IMPORT_SUCCESS = "checkPassAndImportSuccess";

    @ApiOperation("根据 动因分组表主键 获取 动因列表")
    @GetMapping("list/{driverGroupId}/{modelId}")
    public Map<String, Object> getDriverListByDriverGroupId(@PathVariable("driverGroupId") String driverGroupId,@PathVariable("modelId") String modelId) {
        //获取动因列表
        List<Driver> driverListByDriverGroupId = abcDriverService.getDriverListByDriverGroupId(driverGroupId,modelId);

        //计算所有动因项个数，用于生成ncell表样
        long count = driverListByDriverGroupId.stream()
                .map(Driver::getDriverItemList)//一对一转换
                .filter(Objects::nonNull) // 过滤空值
                .flatMap(Collection::stream) //一对多转换
                .count();//计算

        //返回给前端的数据
        HashMap<String, Object> result = new HashMap<>();
        result.put("showList", driverListByDriverGroupId);
        result.put("totalCount", count);

        return result;
    }

    @ApiOperation("自动生成动因编码")
    @PostMapping("autoGenDriverCode/{modelId}")
    public Map<String, Object> autoGenDriverCode(@PathVariable("modelId") String modelId,@RequestBody List<Driver> curPageAllDriverList) {
        String newDriverCode = abcDriverService.autoGenDriverCode(modelId,curPageAllDriverList);

        //返回给前端的数据
        HashMap<String, Object> result = new HashMap<>();
        result.put("newDriverCode", newDriverCode);

        return result;
    }


    @ApiOperation("批量添加动因和动因项")
    @PostMapping("batchAdd/{driverGroupId}")
    public void batchAddDriversAndDriverItems(@PathVariable("driverGroupId") String driverGroupId,@RequestBody List<Driver> drivers) {
        abcDriverService.batchSaveDriversAndDriverItems(driverGroupId,drivers);
    }

    @ApiOperation("导入")
    @PostMapping("import/{modelId}/{currentDriverGroupId}")
    public Map<String, Object> importData(@PathVariable("modelId") String modelId,
                                          @PathVariable("currentDriverGroupId") String currentDriverGroupId,
                                          @RequestParam("file") MultipartFile file) {

        //返回给前端的数据
        HashMap<String, Object> result = new HashMap<>();
        boolean isSuccess = true;

        try {
           abcDriverService.processImportData(modelId, currentDriverGroupId, file);
        } catch (ABCException e) {
            isSuccess = false;
            result.put("errorInfo", e.getMessage());
        } finally {
            result.put(CHECK_PASS_AND_IMPORT_SUCCESS, isSuccess);
        }

        return result;
    }

    @ApiOperation("导出")
    @PostMapping("export/{driverGroupId}/{modelId}")
    public void exportData(@PathVariable("driverGroupId")String driverGroupId,@PathVariable("modelId")String modelId, HttpServletResponse response) {
        abcDriverService.processExportData(driverGroupId,modelId, response);
    }


    @ApiOperation("动因编码检查_检查当前模型中全部动因编码是否存在冲突")
    @PostMapping("driverCodeCheckViaExistedDrivers/{modelId}")
    public Map<String, Object> driverCodeCheckViaExistedDrivers(@PathVariable("modelId") String modelId,
                                                                @RequestBody List<Driver> driverList) {
        boolean isNotReapted = abcDriverService.driverCodeCheckViaExistedDrivers(modelId, driverList);

        //返回给前端的数据
        HashMap<String, Object> result = new HashMap<>();
        result.put("checkValue", isNotReapted);

        return result;
    }

    @ApiOperation("动因编码检查_检查当前模型中非当前动因分组的动因编码是否存在冲突")
    @PostMapping("driverCodeCheckViaOtherExistedDrivers/{modelId}/{driverGroupId}")
    public Map<String, Object> driverCodeCheckViaOtherExistedDrivers(@PathVariable("modelId") String modelId,
                                                                     @PathVariable("driverGroupId") String driverGroupId,
                                                                     @RequestBody List<Driver> driverList) {
        DriverCheckVo driverCheckVo = abcDriverService.driverCodeCheckViaExistedDriversExcCurrGroup(modelId,driverGroupId, driverList);

        //返回给前端的数据
        HashMap<String, Object> result = new HashMap<>();
        result.put("driverCheckVo", driverCheckVo);

        return result;
    }

    @ApiOperation("动因编码检查_检查当前模型中分摊关系是否存在引用")
    @PostMapping("driverCodeCheckViaRelation/{modelId}")
    public Map<String, Object> driverCodeCheckViaRelation(@PathVariable("modelId") String modelId,
                                                          @RequestBody List<Driver> driverList) {

        List<String> driverCodeList = new ArrayList<>();
        driverList.forEach(driver -> driverCodeList.add(driver.getCode()));

        Map<String, Boolean> quoteInfor = abcRelationService.hasRelationByDriverID(modelId, driverCodeList);

        AtomicBoolean hasQuote = new AtomicBoolean(false);
        List<String> quotedDriverNames = new ArrayList<>();
        quoteInfor.forEach((key, value) -> {
            if (Boolean.TRUE.equals(value)) {
                if (!hasQuote.get()) {
                    hasQuote.set(value);
                }
                driverList.stream()
                        .filter(filterItem -> filterItem.getCode().equals(key))
                        .forEach(driver -> quotedDriverNames.add(driver.getName()));
            }
        });


        //返回给前端的数据
        HashMap<String, Object> result = new HashMap<>();
        result.put("hasQuote", hasQuote.get());
        result.put("quotedDriverNames", quotedDriverNames);

        return result;
    }
}
